package com.atguigu.gmall.index.config;

import com.atguigu.gmall.index.service.IndexService;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author 刘嘉乐
 * @Date 2022/1/12 16:41
 * @Version 1.0
 */
@Configuration
public class BloomFilterConfig {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IndexService indexService;
    private static final String KEY_PREFIX = "index:cates:";
    @Bean
    public RBloomFilter bloomFilter(){
                            // 获取布隆过滤器并起名字
        RBloomFilter<String> bloomFilter = this.redissonClient.getBloomFilter("index:bf");
        bloomFilter.tryInit(1000,0.03);
        List<CategoryEntity> categoryEntities = this.indexService.queryLvl1Categories();
        if (!CollectionUtils.isEmpty(categoryEntities)){
            categoryEntities.forEach(categoryEntity -> {
                bloomFilter.add(KEY_PREFIX+categoryEntity.getId());
            });
        }
         return bloomFilter;
    }
}
